require('../js/global.js');
var http = require('http');
var url = require('url');
var Iconv = require('iconv').Iconv;
var ServerManager = require('../js/servers.js').ServerManager;

global.gToolPath = util.format('%s/tools', config.system.home);
global.gProcessName = 'transfer';
global.gServers = new ServerManager();
global.gHub = require('./hub');

global.gMysqlPool = require('./pool.js');

gServers.load({slave:true, native:true}, function(err) {
    if (err) {
        LOG(util.format('load failed, %j', err));
        process.exit(1);
    }

    async.series([
        function(cb) {
            gMysqlPool.init("login", function(err) {
                cb(err);
            });
        }
    ], function(err){
        if (err) {
            LOG(util.format('load failed, %j', err));
            process.exit(1);
        } else {
            startWebServer({
                name: gProcessName,
                port: config.platform.gm.transfer.port,
                timeout: 1200*1000,
            });

            setInterval(function(){
                gServers.loadGame(function(err) {});
            }, 600*1000);
        }
    });
});

function startWebServer(options) {
    var name = options.name;
    var port = options.port;
    var timeout = options.timeout;

    LOG(util.format('%s start', name));
    var webServer = http.createServer(function(req, res) {
        var reqObj = url.parse(req.url, true);
        var query = reqObj.query || {};
        var path = reqObj.pathname.substring(1);

        if( req.method == 'POST' ) {
            req.connection.destroy();
            return;
        }

        if (false && !common.verifyGatewayAuth((new Date()).format('yyyy-MM-dd hh'), query.key)) {
            res.writeHead(404, {"Content-Type": "text/plain"});
            res.end(JSON.stringify({code:404, desc:'auth failed', path:path}));
            return;
        }
         
        req.on('end', function() {
            var resp = {code:0, desc:'', data:''};
           
            var handler = null;
            switch (path) {
            case 'onlineCount':
                handler = gHub.gateway[path];
                break;
            default:
                handler = gHub.manage[path]; 
            }

            if (!handler) {
                resp.code = 2; resp.desc = "path invalid";
                res.writeHead(404, {"Content-Type": "text/plain"});
                res.end(JSON.stringify(resp));
                return;
            }

            handler(query, resp, function() {
                if (resp.plain) {
                    res.writeHead(200, common.defaultHeaders);
                    res.end(resp.data);
                } else {
                    res.writeHead(200, common.htmlHeaders);
                    res.end(resp.ispage ? resp.data : JSON.stringify(resp));
                }

            });
        });

        req.resume();

    });
    
    webServer.listen(port);
    webServer.timeout = timeout;

    var pidFile = util.format('%s.pid', name);
    process.on('SIGINT', function() {
        exit();
    });

    process.on('SIGTERM', function() {
        exit();
    });

    process.on('uncaughtException', function (err) {  
        LOG(err.stack);        
    });

    function exit() {
        LOG(util.format('%s shutdown', name));
        fs.existsSync(pidFile) && fs.unlinkSync(pidFile);
        process.exit();
    }
}

